package com.yeyks.commonReference.service.order.impl;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.google.common.collect.Lists;
import com.yeyks.common.dto.mq.GrabTheOrderBToCMessage;
import com.yeyks.common.exception.ServiceException;
import com.yeyks.common.result.OrderPickWebSocket;
import com.yeyks.common.utils.ObjectConvertUtil;
import com.yeyks.common.utils.RedisUtil;
import com.yeyks.commonReference.append.rocketmq.service.producer.MQProducerService;
import com.yeyks.commonReference.service.config.ConfigService;
import com.yeyks.order.dal.domain.OrderPickRecord;
import com.yeyks.order.dal.dao.OrderPickRecordMapper;
import com.yeyks.commonReference.service.order.OrderPickRecordService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;


/**
 * <p>
 * 酒店抢单记录表 服务实现类
 * </p>
 *
 * @author yun
 * @since 2019-08-07
 */
@Service
@Slf4j
public class OrderPickRecordServiceImpl extends ServiceImpl<OrderPickRecordMapper, OrderPickRecord> implements OrderPickRecordService {

    @Autowired
    private RedisUtil redisUtil;
    @Autowired
    private ConfigService configService;
    @Autowired
    private MQProducerService mqProducerService;
    private static final String redisOrderPickRecordOperating = "redisLock:OrderPickRecordService:robOrder";

    /**
     * 酒店快速抢单(抢单成功返回true,失败返回错误信息)
     *
     * @param orderPickWebSocket
     */
    @Override
    public void robOrder(OrderPickWebSocket orderPickWebSocket) {
        //获取抢单超时的时间的时间(毫秒)
        Integer overTime = configService.getRobOverTime();
        //抢单超时提示抢单失败
        long timestamp = orderPickWebSocket.getTimestamp() + overTime;
        if (System.currentTimeMillis() > timestamp) {
            throw new ServiceException("抢单超时，已不能抢单");
        }
        List<OrderPickRecord> orderPickRecords = Lists.newArrayList();
        if (null != orderPickWebSocket.getRoomIds() && orderPickWebSocket.getRoomIds().size() > 0) {
            if (orderPickWebSocket.getRoomIds().size() == 1) {
                OrderPickRecord orderPickRecord = getOrderPickRecord(orderPickWebSocket);
                if (null != orderPickRecord) {
                    orderPickRecord.setRoomId(orderPickWebSocket.getRoomIds().get(0));
                    orderPickRecord.setSourceRoomId(String.valueOf(orderPickWebSocket.getRoomIds().get(0)));
                    orderPickRecords.add(orderPickRecord);
                }
            } else {
                for (Integer roomId : orderPickWebSocket.getRoomIds()) {
                    OrderPickRecord orderPickRecord = getOrderPickRecord(orderPickWebSocket);
                    if (null != orderPickRecord) {
                        orderPickRecord.setRoomId(roomId);
                        orderPickRecord.setSourceRoomId(String.valueOf(roomId));
                        orderPickRecords.add(orderPickRecord);
                    }
                }
            }
        }
        if (orderPickRecords.size() == 0) {
            log.info("生成抢单记录异常：orderPickWebSocket = {}", orderPickWebSocket);
            throw new ServiceException("生成抢单记录异常");
        }
        redisUtil.runWithLock(redisOrderPickRecordOperating, () -> {
            List<Integer> ids = Lists.newArrayList();
            orderPickRecords.forEach(e -> {
                OrderPickRecord orderPickRecord = baseMapper.selectOne(new QueryWrapper<OrderPickRecord>().eq(OrderPickRecord.HOTEL_ID, e.getHotelId())
                        .eq(OrderPickRecord.ROOM_ID, e.getRoomId())
                        .eq(OrderPickRecord.TIMESTAMP, e.getTimestamp())
                        .eq(OrderPickRecord.USER_ID, e.getUserId()));
                if (null == orderPickRecord) {
                    if (1 != baseMapper.insert(e)) {
                        throw new ServiceException("写入抢单记录异常");
                    }
                    ids.add(e.getId());
                }
            });
            //mq给C端发送消息
            if (ids.size() > 0) {
                GrabTheOrderBToCMessage errorMessage = new GrabTheOrderBToCMessage(3, orderPickWebSocket.getUserId(), orderPickWebSocket.getTimestamp(), ids);
                mqProducerService.webToCSendSimpleMsg(JSONUtil.toJsonStr(errorMessage));
            }
            return true;
        });
    }

    private OrderPickRecord getOrderPickRecord(OrderPickWebSocket orderPickWebSocket) {
        Date date = new Date();
        OrderPickRecord orderPickRecord = ObjectConvertUtil.convertObject(orderPickWebSocket, OrderPickRecord.class);
        if (null != orderPickRecord) {
            orderPickRecord.setCheckIn(new Date(orderPickWebSocket.getCheckIn()));
            orderPickRecord.setCheckOut(new Date(orderPickWebSocket.getCheckOut()));
            orderPickRecord.setGmtCreate(date);
            orderPickRecord.setGmtModified(date);
            if (StrUtil.isBlank(orderPickRecord.getSourceType())) {
                log.info("酒店的sourceType为null,orderPickRecord = {}", orderPickRecord);
            }
            orderPickRecord.setSourceType(orderPickWebSocket.getSourceType());
            orderPickRecord.setSoureHotelId(orderPickWebSocket.getSoureHotelId());
        }
        return orderPickRecord;
    }

}
